package ca.skygazer.server;

import java.security.Principal;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;

import ca.skygazer.client.SgUserService;
import ca.skygazer.shared.account.SgUser;
import ca.skygazer.shared.coords.AzAltCoord;
import ca.skygazer.shared.coords.LatLonCoord;
import ca.skygazer.shared.coords.RaDecCoord;
import ca.skygazer.shared.coords.XYCoord;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class SgUserServiceImpl  extends RemoteServiceServlet implements SgUserService {

	public String updateUser(SgUser user){
		PersistenceManager pm=PMF.get().getPersistenceManager();
		pm.makePersistent(user);
		return user.getNickname()+" updated";
	}
	
	public SgUser getUser(){
		PersistenceManager pm=PMF.get().getPersistenceManager();
		
		SgUser skygazerUser = null;
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

	    Query query = pm.newQuery(SgUser.class);
	    query.setFilter("email == emailParam");
	    query.declareParameters("String emailParam");

	    try {
	        List<SgUser> results = (List<SgUser>) query.execute(user.getEmail());
	        if (results.iterator().hasNext()) {
	            for (SgUser su : results) {
	            	skygazerUser = pm.detachCopy(su);
	            	skygazerUser.setLastLogin(new Date());
	            	pm.makePersistent(skygazerUser);
	            	//System.out.println("Locations: " + skygazerUser.getViewingLocations().size());
	            }
	        } else {
	            skygazerUser=new SgUser();
	            skygazerUser.setEmail(user.getEmail());
	            skygazerUser.setNickname(user.getNickname());
	            skygazerUser.setLastLogin(new Date());
	            pm.makePersistent(skygazerUser);
	        }
	    } finally {
	        query.closeAll();
	        pm.close();
	    }		
		
		return skygazerUser;
	}

	public boolean checkLogin(){
	    HttpServletRequest request = this.getThreadLocalRequest();	    
	    Principal principal = request.getUserPrincipal();
        if (principal != null) {        	
            return (true);
        } else {
            return (false);
        }
		
	}
	
	public String getLoginUrl(String homeUrl){
	    HttpServletRequest request = this.getThreadLocalRequest();	    
		UserService userService = UserServiceFactory.getUserService();
		
        if (request.getUserPrincipal() != null) {
            return (null);
        } else {
//            return ("<head><style>body {color: red;}</style></head>" +"<body>Please <a href=\"" + userService.createLoginURL(homeUrl) + "?gwt.codesvr=127.0.0.1:9997\">sign in</a></body>");
            return ("<p>Please <a href=\"" + userService.createLoginURL(homeUrl) + "\">sign in</a>.</p>");
        }		
	}
	
	public String getLogoutUrl(String homeUrl){
		UserService userService = UserServiceFactory.getUserService();		
        return ("<head><style>body {color: red;}</style></head><body>Click <a href=\"" + userService.createLogoutURL(homeUrl) + "\">here</a> to log out.</body>");
	}
	
	@Override
	public String dummyService(AzAltCoord arg1, 
			LatLonCoord arg2,
			RaDecCoord arg3,
			XYCoord arg4,
			Vector<LatLonCoord> vector,
			List<LatLonCoord> list
			) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		return null;
	}
}
